function allCovs = GenerateCovariates_MainExp(saveBool, stimDur, sequenceFiles)
%
%   For 3-target sequences:
%       After Blank-blocks, 11 overlap trials are added
%       After Target trials, 9 overlap trials are added
%
%   For 4-target sequences:
%       After Blank-blocks, 8 overlap trials are added
%       After Target trials, 8 overlap trials are added
%
%   For 5-target sequences:
%       After Blank-blocks, 6 overlap trials are added
%       After Target trials, 7 overlap trials are added
%
%   _______________________________________________
%   by Marcelo G Mattar (07/24/2012)
%   mattar@sas.upenn.edu


%% CHECK INPUTS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

if nargin < 3
    sequenceFiles = {...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/ITIanalysis/Experiment/config/seqs/ITI700a.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/ITIanalysis/Experiment/config/seqs/ITI700b.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/ITIanalysis/Experiment/config/seqs/ITI1050a.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/ITIanalysis/Experiment/config/seqs/ITI1050b.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/ITIanalysis/Experiment/config/seqs/ITI1400a.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/ITIanalysis/Experiment/config/seqs/ITI1400b.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/ITIanalysis/Experiment/config/seqs/ITI2100a.txt' ...
        '/Users/marcelomattar/Dropbox/Marcelo/UPenn/Documents/Projects/ITIanalysis/Experiment/config/seqs/ITI2100b.txt' ...
        };
else
    if ~iscell(sequenceFiles)
        sequenceFiles = cellstr(sequenceFiles);
    end
end

if nargin < 2
    stimDur = [0.700;0.700;1.050;1.050;1.400;1.400;2.100;2.100];
end

if nargin < 1
    saveBool = 0;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

numFiles = length(sequenceFiles);


for seqnum = 1:numFiles

%% COVARIATES OF NO INTEREST
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    % Load the sequence
    thisSeq = double(importdata(sequenceFiles{seqnum}));
    
    % blankTrials: one for every blank trial, zero otherwise
    blankTrials = thisSeq==0;
    % targetTrials: one for every target trial, zero otherwise
    targetTrials = thisSeq==-1;
    
    % Convert from logical to double
    targetTrials = targetTrials + 0;
    
    % Define block lengths
    blankBlockLen = 4;
    targetBlockLen = 4;
    
    % Create targetRefreshTrials covariate
    targetRefreshTrials = cell(targetBlockLen,1);
    for thisCov = 1:targetBlockLen
        targetRefreshTrials{thisCov} = zeros(size(thisSeq));
        targetRefreshTrials{thisCov}(find(thisSeq==-1) + thisCov) = 1;
    end
    
    % Create blankRefreshTrials covariate
    blankRefreshTrials = cell(blankBlockLen,1);
    for thisCov = 1:blankBlockLen
        blankRefreshTrials{thisCov} = zeros(size(thisSeq));
        endOfBlankBlocks = findEndOfBlankBlock(thisSeq);
        blankRefreshTrials{thisCov}(endOfBlankBlocks + thisCov) = 1;
    end
    
    

%% MAIN EFFECT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    mainEffect = ~(blankTrials + targetTrials + sum([blankRefreshTrials{:}],2) + sum([targetRefreshTrials{:}],2));
    %if sum(mainEffect) ~= 128
    %    error('The number of valid trials is not 128. Check for errors in the code');
    %end
    
    % Convert from logical to double
    mainEffect = mainEffect + 0;
    

%% CARRYOVER COVARIATES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    % carryOver 1
    carryOver1 = thisSeq - [thisSeq(end); thisSeq(1:(end-1))];
    carryOver1(carryOver1 ~= 0) = 1;
    carryOver1(carryOver1 ~= 1) = -1;
    carryOver1 = carryOver1 .* mainEffect;
    
    % carryOver 2
    carryOver2 = thisSeq - [thisSeq((end-1):end); thisSeq(1:(end-2))];
    carryOver2(carryOver2 ~= 0) = 1;
    carryOver2(carryOver2 ~= 1) = -1;
    carryOver2 = carryOver2 .* mainEffect;
    
    % carryOver 3
    carryOver3 = thisSeq - [thisSeq((end-2):end); thisSeq(1:(end-3))];
    carryOver3(carryOver3 ~= 0) = 1;
    carryOver3(carryOver3 ~= 1) = -1;
    carryOver3 = carryOver3 .* mainEffect;
    
    % carryOver 4
    carryOver4 = thisSeq - [thisSeq((end-3):end); thisSeq(1:(end-4))];
    carryOver4(carryOver4 ~= 0) = 1;
    carryOver4(carryOver4 ~= 1) = -1;
    carryOver4 = carryOver4 .* mainEffect;
    
    % carryOver 5
    carryOver5 = thisSeq - [thisSeq((end-4):end); thisSeq(1:(end-5))];
    carryOver5(carryOver5 ~= 0) = 1;
    carryOver5(carryOver5 ~= 1) = -1;
    carryOver5 = carryOver5 .* mainEffect;
    
    % carryOver 6
    carryOver6 = thisSeq - [thisSeq((end-5):end); thisSeq(1:(end-6))];
    carryOver6(carryOver6 ~= 0) = 1;
    carryOver6(carryOver6 ~= 1) = -1;
    carryOver6 = carryOver6 .* mainEffect;
    
    

%% MEAN CENTER ALL COVARIATES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Mean center each covariate
    %{
    thisMean = sum(afterBlanks{seqnum}(afterBlanks{seqnum} ~= 0))/sum(afterBlanks{seqnum} ~= 0);
    afterBlanks{seqnum}(afterBlanks{seqnum} ~= 0) = afterBlanks{seqnum}(afterBlanks{seqnum} ~= 0) - thisMean;
    
    thisMean = sum(targetTrials{seqnum}(targetTrials{seqnum} ~= 0))/sum(targetTrials{seqnum} ~= 0);
    targetTrials{seqnum}(targetTrials{seqnum} ~= 0) = targetTrials{seqnum}(targetTrials{seqnum} ~= 0) - thisMean;
    
    thisMean = sum(afterTargets{seqnum}(afterTargets{seqnum} ~= 0))/sum(afterTargets{seqnum} ~= 0);
    afterTargets{seqnum}(afterTargets{seqnum} ~= 0) = afterTargets{seqnum}(afterTargets{seqnum} ~= 0) - thisMean;
    
    thisMean = sum(carryOver1{seqnum}(carryOver1{seqnum} ~= 0))/sum(carryOver1{seqnum} ~= 0);
    carryOver1{seqnum}(carryOver1{seqnum} ~= 0) = carryOver1{seqnum}(carryOver1{seqnum} ~= 0) - thisMean;
    %}
    

%% SAVE RESULTS TO STRUCTURE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    
    i = max(strfind(sequenceFiles{seqnum}, '/'));
    j = max(strfind(sequenceFiles{seqnum}, '.'));
    sequenceName = sequenceFiles{seqnum}((i+1):(j-1));
    %{
    eval(['allCovs.' sequenceName '.mainEffect = mainEffect;']);
    eval(['allCovs.' sequenceName '.carryOver1 = carryOver1;']);
    eval(['allCovs.' sequenceName '.carryOver2 = carryOver2;']);
    eval(['allCovs.' sequenceName '.carryOver3 = carryOver3;']);
    eval(['allCovs.' sequenceName '.carryOver4 = carryOver4;']);
    eval(['allCovs.' sequenceName '.carryOver5 = carryOver5;']);
    eval(['allCovs.' sequenceName '.carryOver6 = carryOver6;']);
    eval(['allCovs.' sequenceName '.targetTrials = targetTrials;']);
    for i=1:targetBlockLen
        eval(['allCovs.' sequenceName '.targetRefresh' num2str(i) ' = targetRefreshTrials{' num2str(i) '};']);
    end
    for i=1:blankBlockLen
        eval(['allCovs.' sequenceName '.blankRefresh' num2str(i) ' = blankRefreshTrials{' num2str(i) '};']);
    end
    %}

%% SAVE RESULTS TO EXTERNAL FILE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    if saveBool
        if ~exist('./covariates/', 'dir')
            mkdir('./covariates/');
        end
        if ~exist('./covariates/mainExp/', 'dir')
            mkdir('./covariates/mainExp/');
        end
        
        % File IDs for covariates of interest
        mainEffect_fileID = fopen(['./covariates/mainExp/' sequenceName '_mainEffect.txt'],'w');
        carryOver1_fileID = fopen(['./covariates/mainExp/' sequenceName '_carryOver1.txt'],'w');
        carryOver2_fileID = fopen(['./covariates/mainExp/' sequenceName '_carryOver2.txt'],'w');
        carryOver3_fileID = fopen(['./covariates/mainExp/' sequenceName '_carryOver3.txt'],'w');
        carryOver4_fileID = fopen(['./covariates/mainExp/' sequenceName '_carryOver4.txt'],'w');
        carryOver5_fileID = fopen(['./covariates/mainExp/' sequenceName '_carryOver5.txt'],'w');
        carryOver6_fileID = fopen(['./covariates/mainExp/' sequenceName '_carryOver6.txt'],'w');
        
        % File IDs for covariates of no interest
        targetTrials_fileID = fopen(['./covariates/mainExp/' sequenceName '_targetTrials.txt'],'w');
        targetRefreshTrials_fileID = zeros(size(targetRefreshTrials));
        for i=1:targetBlockLen
            targetRefreshTrials_fileID(i) = fopen(['./covariates/mainExp/' sequenceName '_targetRefresh' num2str(i) '.txt'],'w');
        end
        blankRefreshTrials_fileID = zeros(size(blankRefreshTrials));
        for i=1:blankBlockLen
            blankRefreshTrials_fileID(i) = fopen(['./covariates/mainExp/' sequenceName '_blankRefresh' num2str(i) '.txt'],'w');
        end
        
        % Populate the files
        for trial=1:(length(thisSeq)-1)
            % Covariates of interest
            if(mainEffect(trial)~=0); fprintf(mainEffect_fileID,'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),mainEffect(trial)); end
            if(carryOver1(trial)~=0); fprintf(carryOver1_fileID,'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),carryOver1(trial)); end
            if(carryOver2(trial)~=0); fprintf(carryOver2_fileID,'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),carryOver2(trial)); end
            if(carryOver3(trial)~=0); fprintf(carryOver3_fileID,'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),carryOver3(trial)); end
            if(carryOver4(trial)~=0); fprintf(carryOver4_fileID,'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),carryOver4(trial)); end
            if(carryOver5(trial)~=0); fprintf(carryOver5_fileID,'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),carryOver5(trial)); end
            if(carryOver6(trial)~=0); fprintf(carryOver6_fileID,'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),carryOver6(trial)); end
            
            % Covariates of no interest
            if(targetTrials(trial)~=0); fprintf(targetTrials_fileID,'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),targetTrials(trial)); end
            for file=1:length(targetRefreshTrials_fileID)
                if(targetRefreshTrials{file}(trial)~=0); fprintf(targetRefreshTrials_fileID(file),'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),targetRefreshTrials{file}(trial)); end
            end
            for file=1:length(blankRefreshTrials_fileID)
                if(blankRefreshTrials{file}(trial)~=0); fprintf(blankRefreshTrials_fileID(file),'%f\t%f\t%f\n',stimDur(seqnum)*(trial-1),stimDur(seqnum),blankRefreshTrials{file}(trial)); end
            end
        end
        
        fclose('all');
        
    end
    

end

display('Done');





function endOfBlankBlocks = findEndOfBlankBlock(sequence)

    startOfBlankBlocks = [];
    endOfBlankBlocks = [];
    
    if sequence(1) == 0; % If the first element is a blank
        startOfBlankBlocks = 1;
    end
    
    for i=1:(length(sequence)-1)
        if (sequence(i)~=0) && (sequence(i+1)==0)
            startOfBlankBlocks = [startOfBlankBlocks, (i+1)];
        end
        if (sequence(i)==0) && (sequence(i+1)~=0)
            endOfBlankBlocks = [endOfBlankBlocks, i];
        end
    end
